package com.love.zywanandroid.fragment

import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.google.gson.Gson
import com.xw.banner.BannerConfig
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseFragment
import com.zat.mes.andrmes.data.HomeBtnBean
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.dofun.main.MessageNotifActivity
import com.zat.mes.andrmes.dofun.main.adapter.HomeVpAdapter
import com.zat.mes.andrmes.dofun.main.vm.BindMachineModel
import com.zat.mes.andrmes.dofun.main.vm.HomeModel
import com.zat.mes.andrmes.dofun.main.vm.TodoModel
import com.zat.mes.andrmes.dofun.todo.TodoNewActivity
import com.zat.mes.andrmes.dofun.todo.adapter.TodoAdapter
import com.zat.mes.andrmes.event.LoadingEventMessage
import com.zat.mes.andrmes.event.TodoEventMessage
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.imageloader.BannerGlideImageLoader
import com.zat.mes.andrmes.utils.PreferencesUtil
import com.zat.mes.andrmes.utils.ViewUtil
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.item_flipper_home.view.*
import kotlinx.android.synthetic.main.layout_title.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @author zy
 * @date :2019-02-13 10:43
 * @description: homefragment
 */
class HomeFragment : BaseFragment() {

    /**
     * 待办事项model
     */
    private var todoModel: TodoModel? = null
    private var empId: Long = 0
    override fun getViewId(): Int {
        return R.layout.fragment_home
    }

    /**
     * 初始化数据
     */
    override fun initData() {
        EventBus.getDefault().register(this)
        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        empId = loginResultBean.empid
        val empName = loginResultBean.empname
        recylerHome.layoutManager = LinearLayoutManager(context)
        val todoAdapter = TodoAdapter(R.layout.item_todo_fragment, empId, empName)
        recylerHome.adapter = todoAdapter
        todoModel = ViewModelProvider(this).get(TodoModel::class.java)

        todoModel?.getTodoList()?.observe(this, Observer {
            todoAdapter.setNewData(ArrayList())
            if (it != null && it.result != null && it.result != null)
                if (it.result.size > 2) {
                    val subList = it.result.subList(0, 2)
                    todoAdapter.addData(subList)
                } else {
                    todoAdapter.addData(it.result)
                }
        })
        todoAdapter?.loadMoreModule?.isEnableLoadMore = false
        todoModel?.loadTodoList(1, 2, empId, "0")


        addListener()
        setBanner()
        loadModel()
    }

    /**
     * 加载数据model
     */
    private fun loadModel() {
        showLoading()
        val homeModel = ViewModelProvider(this).get(HomeModel::class.java)
        val messageLiveData = homeModel.getMessageList();
        messageLiveData.observe(this, Observer {
            //            closeLoading()
            if (it != null) {
                //设置通知公告
                for (index in it.items?.indices) {
                    val inflate =
                        LayoutInflater.from(context).inflate(R.layout.item_flipper_home, null)
                    flipperHome.addView(inflate)
                    val itemBean = it.items.get(index);
                    inflate.tvMessageHome.text = itemBean.title
//                    when (it.items.get(index).type) {
//                        "1" -> inflate.tvMsgTypeHome.text = getString(R.string.msg_notification)
//                        "2" -> inflate.tvMsgTypeHome.text = getString(R.string.msg_safe)
//                        "3" -> inflate.tvMsgTypeHome.text = getString(R.string.msg_activity)
//                    }
                    inflate.tvMsgTypeHome.text = itemBean.typeName
                    inflate.setOnClickListener {
                        val intent = Intent(context, MessageNotifActivity::class.java)
                        intent.putExtra(CompanionType.INTENT_EXTRA_BEAN, itemBean)
                        startFragmentActivity(intent)
                    }
                }
                //设置4秒滚动
                flipperHome.setFlipInterval(4000);
                flipperHome.startFlipping()
            }
        })
        //获取首页菜单数据
        homeModel.getHomeBtnList().observe(this, Observer {
            closeLoading()
            it?.let {
                setviewpager(it)
            }

        })




    }
    //设置监听
    private fun addListener() {
        vpHome.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                //切换点
                currentDoc(position)
            }
        })
        btnMoreHome.setOnClickListener {
            startFragmentActivity(Intent(context, TodoNewActivity::class.java))
        }
    }
    //设置viewpager 一组8个菜单
    private fun setviewpager(list: MutableList<HomeBtnBean>) {
//        list.add(HomeBtnBean("",ArrayList(),"","","","领纱","yarnIn","","",""))
//        list.add(HomeBtnBean("",ArrayList(),"","","","退纱","yarnUn","","",""))
//        list.add(HomeBtnBean("",ArrayList(),"","","","机器检查","macCheck","","",""))
//        list.add(HomeBtnBean("",ArrayList(),"","","","日机维护","macDayCare","","",""))
//        list.add(HomeBtnBean("",ArrayList(),"","","","周机维护","macWeekCare","","",""))
        var data: MutableList<MutableList<HomeBtnBean>> = ArrayList()
        val pagerCount = list.size / 8 + if (list.size % 8 > 0) 1 else 0
        for (i in 0..pagerCount - 1) {
            var btnList: MutableList<HomeBtnBean> = ArrayList()
            if (i * 8 + 8 >= list.size) {
                btnList = list.subList(i * 8, list.size)
            } else {
                btnList = list.subList(i * 8, i * 8 + 8)
            }
            data.add(btnList)
        }
        val myAdapter = HomeVpAdapter()
        myAdapter.setList(data)
        vpHome.adapter = myAdapter
        setDoc(pagerCount)
    }

    /**
     * 设置首页banner
     */
    private fun setBanner() {
        bannerHome.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                bannerHome.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val layoutParams: LinearLayout.LayoutParams =
                    bannerHome.layoutParams as LinearLayout.LayoutParams
                layoutParams.height = (bannerHome.width / 2.0f).toInt()
                Log.e("viewTreeObserver", "ss")
            }
        })

        var datas: MutableList<Any> = ArrayList()
        datas.add(R.mipmap.pic_shouye_lunbotushili)
        bannerHome.setImageLoader(BannerGlideImageLoader())
        bannerHome.setDelayTime(5000)
        bannerHome.setImages(datas)
        bannerHome.setBannerStyle(BannerConfig.CUSTOM_INDICATOR);
        bannerHome.start()

    }

    /**
     * 设置点
     */
    private fun setDoc(count: Int) {
        llDocVpHome.removeAllViews()
        for (d in 0..count - 1) {
            var imageView = ImageView(context)
            llDocVpHome.addView(imageView)
            val layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            if (d != 0) {
                layoutParams.leftMargin = 6
            }
            imageView.layoutParams = layoutParams
            setIvDocBg(d, imageView)

        }

    }

    /**
     * 设置点的资源图片
     */
    private fun setIvDocBg(d: Int, imageView: ImageView) {
        if (vpHome.currentItem == d) {
            imageView.background =
                context?.resources?.getDrawable(R.drawable.indicator_drawable_selected)
        } else {
            imageView.background =
                context?.resources?.getDrawable(R.drawable.indicator_drawable_unselected)
        }
    }

    /**
     * 切换点
     */
    private fun currentDoc(index: Int) {
        for (c in 0..llDocVpHome.childCount) {
            val childAt = llDocVpHome.getChildAt(c)
            if (childAt != null) {
                setIvDocBg(c, childAt as ImageView)
            }
        }
    }

    override fun isOpenTitleBar(): Boolean {
        return false
    }

    override fun initView() {
        val layoutParams = statusBarView.layoutParams as LinearLayout.LayoutParams
        layoutParams.height = ViewUtil.getStatusBarHeight(context!!)
        rlRight.visibility = View.GONE

    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTodoEvent(event: TodoEventMessage) {
        //todolist
        Log.e("eventbus", "todo")
        android.os.Handler()
            .postDelayed(Runnable { todoModel?.loadTodoList(1, 2, empId, "0") }, 500)

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onLoadingEvent(event: LoadingEventMessage?) { /* Do something */
        closeLoading()
    }

    override fun onDestroyView() {
        EventBus.getDefault().unregister(this)
        super.onDestroyView()
    }
}